package com.xfapp.demos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfapp.demos.entity.UserAnswer;
import com.xfapp.demos.mapper.UserAnswerMapper;
import com.xfapp.demos.service.IUserAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 存储用户答题记录的表 服务实现类
 * </p>
 *
 * @author jinYi
 * @since 2025-06-06
 */
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements IUserAnswerService {



    @Resource
    private UserAnswerMapper userAnswerMapper;
    /**
     * 将列表按照指定大小进行分割，返回分块后的子列表集合
     * 定义为静态方法的好处：
     * 1. 可以在不创建对象的情况下直接调用，适合工具类方法
     * 2. 方法不依赖类的实例变量，仅操作传入的参数
     * 3. 提高代码复用性，其他类也可以调用此方法处理列表分割
     */
    public static <T> List<List<T>> splitList(List<T> list, int size) {
        if (list == null || list.isEmpty()) {
            return List.of(); // 返回空列表避免NullPointerException
        }
        if (size <= 0) {
            throw new IllegalArgumentException("分割大小必须大于0");
        }
        int total = list.size();
        return Stream.iterate(0, i -> i + size)
                .limit((total + size - 1) / size)
                .map(i -> list.subList(i, Math.min(i + size, total)))
                .collect(Collectors.toList());
    }

    /**
     * 批量保存或更新用户答题记录，支持事务回滚
     * @param userAnswers 用户答题记录列表
     * @return 操作结果（true 表示成功，false 表示失败）
     * 回去实验一下
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateBatch(List<UserAnswer> userAnswers) {
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper<>();
        for (UserAnswer user : userAnswers) {
            queryWrapper.clear();
            QueryWrapper<UserAnswer> uniqueSentence = queryWrapper.eq("user_id", user.getUserId())
                    .eq("question_id", user.getQuestionId());
            //将查询出的id保存到要修改的id
            UserAnswer FindUserAnswer = userAnswerMapper.selectOne(uniqueSentence);
            if (FindUserAnswer != null) {
                user.setId(FindUserAnswer.getId());
                int updateNumber = userAnswerMapper.updateById(user);
                if (updateNumber == 0) {
                    return false;
                }
            } else {
                int insertNumber = userAnswerMapper.insert(user);
                if (insertNumber == 0) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public Boolean saveOrUpdate(List<UserAnswer> userAnswers) {
        if (userAnswers == null || userAnswers.isEmpty()) {
            return false;
        }
        if (userAnswers.size() > 5) {
            List<List<UserAnswer>> lists = splitList(userAnswers, 5);
            for (List<UserAnswer> list : lists) {
                if (!saveOrUpdateBatch(list)) {
                    return false;
                }
            }
        } else {
            return saveOrUpdateBatch(userAnswers);
        }
        return true;
    }


}
